package com.bytenerd.jianmu.controller;

import com.bytenerd.jianmu.annotation.AuthCheck;
import com.bytenerd.jianmu.common.BaseResponse;
import com.bytenerd.jianmu.common.DeleteRequest;
import com.bytenerd.jianmu.common.ResultUtils;
import com.bytenerd.jianmu.constant.UserConstant;
import com.bytenerd.jianmu.exception.BusinessException;
import com.bytenerd.jianmu.exception.ErrorCode;
import com.bytenerd.jianmu.exception.ThrowUtils;
import com.bytenerd.jianmu.model.dto.*;
import com.bytenerd.jianmu.model.vo.LoginUserVO;
import com.bytenerd.jianmu.model.vo.UserVO;
import com.mybatisflex.core.paginate.Page;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.bytenerd.jianmu.model.entity.User;
import com.bytenerd.jianmu.service.UserService;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

import static com.bytenerd.jianmu.constant.UserConstant.DEFAULT_PASSWORD;

/**
 * 用户表 控制层。
 *
 * @author 程序员bytenerd
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     *  用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("register")
    public BaseResponse register(@RequestBody UserRegisterDTO userRegisterDTO) {
        ThrowUtils.throwIf(userRegisterDTO.getAccount() == null, ErrorCode.PARAMS_ERROR);
        String account = userRegisterDTO.getAccount();
        String password = userRegisterDTO.getPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        long register = userService.register(account, password, checkPassword);
        return ResultUtils.success("注册成功");
    }
    /**
     *  用户登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("login")
    public BaseResponse<LoginUserVO> login(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request) {
        String account =userLoginDTO.getAccount();
        String password =userLoginDTO.getPassword();
        ThrowUtils.throwIf(account == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(password == null, ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userService.login(account, password, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("logout")
    public BaseResponse logout(HttpServletRequest request) {
        return ResultUtils.success(userService.logout(request));
    }

    /**
     * 获取当前登录用户
     * @param request
     * @return
     */
    @GetMapping("get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(user);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 创建用户。
     *
     * @param userAddDTO 用户
     * @return {@code true} 保存成功，{@code false} 保存失败
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("add")
    public BaseResponse<Long> save(@RequestBody UserAddDTO userAddDTO) {
        ThrowUtils.throwIf(userAddDTO == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddDTO,user);
        // 设置默认密码
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据主键更新用户表。
     *
     * @param userUpdateDTO 用户
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> update(@RequestBody UserUpdateDTO userUpdateDTO) {
        if(userUpdateDTO == null || userUpdateDTO.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateDTO,user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 查询所有用户表。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<User> list() {
        return userService.list();
    }

    /**
     * 根据id获取用户。
     *
     * @param id 用户表主键
     * @return 用户表详情
     */
    @GetMapping("get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(Long id) {
        ThrowUtils.throwIf(id <=0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据id获取脱敏用户。
     *
     * @param id 用户表主键
     * @return 用户表详情
     */
    @GetMapping("get/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<UserVO> getUserVOById(Long id) {
        User user = userService.getById(id);
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页查询用户。
     *
     * @param userQueryDTO 分页对象
     * @return 分页对象
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> page(@RequestBody UserQueryDTO userQueryDTO) {
        ThrowUtils.throwIf(userQueryDTO == null, ErrorCode.PARAMS_ERROR);
        Long current = userQueryDTO.getCurrent();
        Long pageSize = userQueryDTO.getPageSize();
        Page<User> userPage = userService.page(Page.of(current, pageSize),
                userService.getQueryWrapper(userQueryDTO));
        //数据脱敏
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotalRow());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 根据id删除用户表。
     *
     * @param deleteRequest
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @PostMapping("remove/{id}")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> remove(@RequestBody DeleteRequest deleteRequest) {
        if(deleteRequest == null || deleteRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(result);
    }
}
